<!-- src/App.vue -->
<template>
  <div class="crypto-dashboard">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <div class="sidebar-logo">
        <img src="@/assets/logo@2x.png" alt="Logo" class="logo-icon" />
        <p class="logo-text">{{ $t('common.dashboard') }}</p>
      </div>
      <nav class="sidebar-nav">
        <ul>
          <li :class="{ active: currentNav === 'Home' }" @click="handleNavTo('Home')">
            <i class="icon-market"></i> {{ $t('common.marketTrend') }}
          </li>
          <li :class="{ active: currentNav === 'CryptoDetail' }" @click="handleNavTo('CryptoDetail')">
            <i class="icon-trend"></i> {{ $t('common.priceTrend') }}
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧主内容 -->
    <div class="main-content">
      <!-- 顶部操作栏 -->
      <header class="top-bar">
        <!-- 搜索栏 -->
        <div class="search-container" ref="searchContainer">
          <img src="@/assets/input-search-icon.png" alt="" srcset="" class="search-icon" />
          <input type="text" v-model="searchQuery" :placeholder="$t('common.searchPlaceholder')" @input="handleSearch" class="search-input">
          <!-- 搜索下拉列表 -->
          <div class="search-dropdown" v-if="showDropdown && filteredSearchResults.length > 0 && searchQuery.trim()">
            <div class="dropdown-item" v-for="coin in filteredSearchResults" :key="coin.id"
              @click="selectSearchResult(coin)">
              <img :src="coin.image" :alt="coin.name" class="dropdown-icon">
              <div class="dropdown-info">
                <div class="dropdown-name">
                  {{ coin.name }}
                  <span class="dropdown-symbol">{{ coin.symbol.toUpperCase() }}</span>
                </div>
                <div class="dropdown-price">${{ coin.current_price | numberFormat(2) }}</div>
              </div>
              <div class="dropdown-change" :class="coin.price_change_percentage_24h >= 0 ? 'up' : 'down'">
                {{ coin.price_change_percentage_24h | numberFormat(2) }}%
              </div>
            </div>
          </div>
        </div>

        <div class="top-bar-right">
          <language-selector />
          <currency-selector />
        </div>
      </header>

      <!-- 统计卡片区 -->
      <section class="stats-cards">
        <router-view @onNavigate="handleNavto"/>
         <!-- <div style="width: 1600px; background: blue;">
            test
         </div> -->
      </section>
    </div>
    <img src="@/assets/bg-bottom.png" class="bg-bottom" alt="" srcset="">
  </div>
</template>

<script>
import axios from 'axios'
import LanguageSelector from '@/components/LanguageSelector.vue';
import CurrencySelector from '@/components/CurrencySelector.vue';
import { mapGetters } from 'vuex'

export default {
  name: "CryptoList",  
  components: {
    LanguageSelector,
    CurrencySelector
  },
  data() {
    return {
      currentNav: localStorage.getItem('currentNav') || "Home", // 当前选中导航：行情/走势
      // 搜索与筛选
      searchQuery: '',
      allCoins: [],
      filteredCoins: [],
      filteredSearchResults: [], // 新增：搜索下拉结果
      showDropdown: false, // 新增：控制下拉显示
      searchDebounceTimer: null, // 新增：搜索防抖定时器
    };
  },
  computed: {
    ...mapGetters(['getCurrency']),
    currentRouteName() {
      return this.$router.currentRoute.name;
    }
  },
  watch: {
    currentNav(newValue, oldValue) {
      if(newValue  === 'CryptoDetail') {
        // 初始化数据
        this.initData()
      }
    }
  },
  filters: {
    numberFormat(value, decimals = 2) {
      if (!value && value !== 0) return '0'
      return value.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
  },
  mounted() {
      // 新增：点击外部关闭下拉列表
      document.addEventListener('click', this.handleClickOutside)
      this.$eventBus.$on('onNavigate', (val) => {
        this.currentNav = val
        localStorage.setItem('currentNav', val)
      } )
  },
  destroyed () {
    this.$eventBus.$off('currencyChange')
    this.$eventBus.$off('onNavigate')
    if (this.searchDebounceTimer) {
      clearTimeout(this.searchDebounceTimer)
      this.searchDebounceTimer = null
    }
  },
  methods: {
    handleNavto() {
      
      console.log("🚀 ~ handleNavto ~ handleNavto:")
    },
    // 初始化数据
    async initData() {
      try {
        // 并行加载数据
        const [coinsResponse] = await Promise.all([
          axios.
          get('http://47.83.150.5:2027/api/v1/coins/market_data?vs_currency=usd&order=market_cap_desc&per_page=1000&page=1',
          {
            headers: {
              'vs_currency': localStorage.getItem('vs_currency') || 'usd', // 自定义头
            }
          }
        )
      ])
      console.log("🚀 ~ initData ~ coinsResponse:", coinsResponse)
        // 处理币种数据
        this.allCoins = coinsResponse.data?.data || []
        console.log("🚀 ~ initData ~  this.allCoins:",  this.allCoins)
        this.filteredCoins = [...this.allCoins]
        this.totalPages = Math.ceil(this.filteredCoins.length / this.itemsPerPage)

      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    handleNavTo(path) {
      if (path === this.currentNav) return
      this.currentNav = path;
      localStorage.setItem('currentNav', path);
      if (path === 'Home') {
        this.$router.push({ name: 'Home' })
      } else {
        
        const allCoins = localStorage.getItem('trendingCoins')
        const bitcoin = JSON.parse(allCoins).find(coin => coin.id === 'bitcoin')
        this.$router.push({
          name: path,
          query: {
            coin: JSON.stringify(bitcoin)
          },
          params: { id: 'bitcoin' }  // 携带id参数
        })
      }
    },
    // 新增：选择搜索结果
    selectSearchResult(coin) {
      this.$eventBus.$emit('topSearchCoin', coin)
      this.showDropdown = false
    },
    // 搜索处理
    handleSearch() {
      if (this.searchDebounceTimer) {
        clearTimeout(this.searchDebounceTimer)
      }
      this.searchDebounceTimer = setTimeout(() => {
        const query = this.searchQuery.toLowerCase().trim()
        if(this.currentNav === 'CryptoDetail') {
            if (!query) {
              this.filteredCoins = [...this.allCoins]
              this.filteredSearchResults = []
              return
            }
            // 过滤结果同时用于列表和下拉框
            const results = this.allCoins.filter(coin =>
              coin.name.toLowerCase().includes(query) ||
              coin.symbol.toLowerCase().includes(query)
            )
      
            this.filteredCoins = results
            // 下拉列表最多显示10项
            this.filteredSearchResults = results.slice(0, 10)
            this.showDropdown = true
        }else {
          this.$eventBus.$emit('topSearchInput', query)
        }
      }, 300)

    },

    // 新增：点击外部关闭下拉
    handleClickOutside(event) {
      if (this.$refs.searchContainer &&
        !this.$refs.searchContainer.contains(event.target)) {
        this.showDropdown = false
      }
    }
  },
};
</script>
<style>
* {
  box-sizing: border-box!important;
  margin: 0;
  padding: 0;
}
main, aside {
  box-sizing: border-box!important;
}
</style>

<style scoped lang="scss">
// 全局样式变量（可抽离到全局SCSS）
$primary-color: #fff;
$bg-color: #f7f3f2;
$card-radius: 16px;
$text-color: #302D2C;
$green: #28a745;
$red: #dc3545;


.crypto-dashboard {
  display: flex;
  min-height: 100vh;
  // height: 1080px;
  background: $bg-color;
  width: 1920px;
  margin: 0 auto;
  position: relative;

  // 左侧导航栏
  .sidebar {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    padding: 24px 26px;
    width: 170px;


    .sidebar-logo {
      display: flex;
      align-items: center;
      flex-direction: column;
      padding: 20px;
      border-bottom: 1px solid #eee;

      .logo-icon {
        width: 56px;
        height: 56px;
        margin-bottom: 7px;
      }

      .logo-text {
        font-size: 20px;
        font-weight: bold;
        color: $text-color;
        height: 28px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 18px;
        line-height: 28px;
        text-align: right;
        font-style: normal;
      }
    }
    .sidebar-nav {
      padding-top: 40px ;
    }
    .sidebar-nav ul {
      list-style: none;
      padding: 0;

      li {
        cursor: pointer;
        color: #666;
        transition: background 0.3s;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 120px;
        height: 50px;

        &:nth-child(1) {
          margin-bottom: 30px;
        }

        &.active {
          background: #f3f0ff;
          font-family: PingFangSC, PingFang SC;
          font-weight: 600;
          font-size: 18px;
          color: #FF722B;
          line-height: 25px;
          text-align: left;
          font-style: normal;
          font-weight: bold;
          width: 120px;
          background: rgba(255, 255, 255, 0.6);
          border-radius: 10px;
          border: 2px solid #FFFFFF;
        }

        i {
          margin-right: 8px;
        }
      }
    }
  }

  // 右侧主内容
  .main-content {
    flex: 1;
    padding: 30px 40px;
    min-width: 0;
    // 顶部操作栏
    .top-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // margin-bottom: 20px;

      .search-box {
        display: flex;
        align-items: center;
        background: #fff;
        border-radius: 8px;
        padding: 8px 12px;
        width: 300px;
        flex: 1;

        .search-icon {
          color: #999;
          margin-right: 8px;
        }

        input {
          border: none;
          outline: none;
          width: 100%;
          font-size: 14px;
        }
      }

      .top-bar-right {
        display: flex;
        align-items: center;
        gap: 20px;
        width: 340px;

        .lang-switch,
        .currency-switch {
          margin-left: 20px;
          display: flex;
          align-items: center;
          cursor: pointer;

          span {
            margin-right: 6px;
            font-size: 14px;
          }

          .arrow-down {
            color: #999;
          }
        }
      }
    }
  }
}
.stats-cards {
  padding: 40px 0;
  width: 100%;
  // overflow-x: scroll;
  // background: rebeccapurple;
}
/* 搜索栏 */
.search-container {
  display: flex;
  // width: 1200px;
  flex: 1;
  position: relative;
  // margin: 0 auto 1rem;
  // width: 1243px;
  height: 54px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 22px;
  border: 2px solid #FFFFFF;
  margin-right: 70px;
}

.search-input {
  width: 100%;
  height: 54px;
  padding-left: 50px;
  padding-right: 20px;
  border-radius: 22px;
  border: 1px solid #FFFFFF;
  // /* 高度的一半，实现完美圆角 */
  // border: 1px solid #e0e0e0;
  font-size: 16px;
  box-sizing: border-box;
  outline: none;
  background: rgba(255,255,255,0.6);
  transition: all 0.3s ease;
}

.search-input::placeholder {
  color: #999;
}

.search-icon {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
  width: 16px;
  height: 16px;
}

.search-input:focus {
  // border-color: #3b82f6;
}

.search-btn {
  background-color: #3b82f6;
  color: white;
  border: none;
  padding: 0 1rem;
  border-radius: 0 8px 8px 0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-btn:hover {
  background-color: #2563eb;
}

/* 搜索下拉列表样式 */
.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  margin-top: 4px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      z-index: 10000;
  max-height: 360px;
  overflow-y: auto;
  border: 1px solid #e2e8f0;
}

/* 下拉列表项样式 */
.dropdown-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f8fafc;
}

/* 下拉列表项内部元素样式 */
.dropdown-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 0.75rem;
  object-fit: cover;
}

.dropdown-info {
  flex: 1;
}

.dropdown-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.dropdown-symbol {
  font-size: 0.8rem;
  color: #64748b;
  margin-left: 0.5rem;
}

.dropdown-price {
  font-size: 0.85rem;
  color: #1e293b;
}

.dropdown-change {
  font-size: 0.85rem;
  font-weight: 500;
  min-width: 50px;
  text-align: right;
}

/* 下拉列表滚动条样式 */
.search-dropdown::-webkit-scrollbar {
  width: 6px;
}

.search-dropdown::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 8px;
}

.search-dropdown::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 8px;
}

.search-dropdown::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
.bg-bottom {
  width: 257px;
  height: 353px;
  position: absolute;
  left: 0;
  top: 727px;
}


@media (min-width: 1920px) {
  .stats-cards {
    &::-webkit-scrollbar {
      display: none!important;
    } 
  }

}
</style>
